package org.jash.ting13.home

import android.view.KeyEvent
import android.widget.Toast
import androidx.paging.PagingData
import com.google.android.material.search.SearchView
import org.jash.ting13.BR
import org.jash.ting13.R
import org.jash.ting13.databinding.FragmentHomeBinding
import org.jash.ting13.entity.HBookEntity
import org.jash.ting13.entity.WorkEntity
import org.jash.utils.CommonAdapter
import org.jash.utils.log
import org.jash.utils.mvi.BaseFragment

class HomeFragment : BaseFragment<FragmentHomeBinding, HomeViewModel>() {
    private lateinit var adapter:CommonAdapter<Any>
    private lateinit var searchAdapter: SearchAdapter
    override fun initData() {
        adapter = CommonAdapter({
            when(it) {
                is List<*> -> R.layout.banner to BR.sliders
                is String -> R.layout.item_title to BR.title
                is WorkEntity -> R.layout.item_work to  BR.work
                is HBookEntity -> R.layout.item_book to  BR.book
                else -> 0 to 0
            }
        }, spanSize = {
            when(it) {
                is List<*> -> 2
                is String -> 2
                else -> 1
            }
        })
        searchAdapter = SearchAdapter()
        viewModel.state.observe(viewLifecycleOwner) {
            when(it) {
                is HomeState.Success -> {
                    adapter.add(it.home.sliders)
                    adapter.add("猜你喜欢")
                    adapter += it.home.words
                    adapter.add("热门连载")
                    adapter += it.home.hot
                    adapter.add("经典完结")
                    adapter += it.home.clazz
                }
                is HomeState.Paging -> {
                    searchAdapter.submitData(viewLifecycleOwner.lifecycle, it.data)
                }
                is HomeState.Failure -> {
                    Toast.makeText(requireContext(), it.message, Toast.LENGTH_SHORT).show()
                }
            }

        }
        viewModel.intent.trySend(HomeIntent.LoadHome)
    }

    override fun initView() {
        binding.recycler.adapter = adapter
        binding.search.editText.setOnEditorActionListener { v, _, event ->
            if ((event?.action ?: KeyEvent.ACTION_UP) == KeyEvent.ACTION_UP) {
                viewModel.intent.trySend(HomeIntent.LoadPaging(v.text.toString()))
            }
            true
        }
        binding.search.addTransitionListener { _, _, state2 ->
            if (state2 == SearchView.TransitionState.SHOWING) {
                searchAdapter.submitData(viewLifecycleOwner.lifecycle, PagingData.empty())
            }
        }

        binding.searchRv.adapter = searchAdapter

    }

}